var Validform_v5 = require("../libs/Validform_v5.3.2_min.js");
var viewMode = require("./payInstallmentView.js");
var bootstrapModals = require("../vendors/bootstrap-modals.js");
var JSON2 = require("../components/json2.js");
var wl = require("../components/winLocation.js");
var $cardInfo, $rateSelect, $userName, $userId, $cvn2, $dateInput, $userPhone, $verifyCode, $creditCard,$vCodeButton;
var rateArray;
var cardInfoForm,countBoxForm;
var orderId, sign, token, amount, nper, totalamount, simplPC;
var unalter;
var CardNum;
var nper;   // 选定期数
var eachPayMoney; // 每期支付金额
var channelNo;
var merNo; // 商戶号
var prdtNo; // 产品号
var getVerifyCodeDJS = 60;
var applyId;
var payId;
$(document).ready(function() {

    initValue();
    viewMode.initView();
    cardInfoForm = $cardInfo.Validform({
        tiptype: 2,
        datatype: {
            "zh2-15": /^[\u4E00-\u9FA5\uf900-\ufa2d]{2,8}$/,
            "sfz": /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/,
            "yxq": /([0][1-9]|[1][0-2])\d{2}/
        }
    });
    countBoxForm = $countBox.Validform({
        tiptype: 2
    });
    getRateInfo();
    createQrcode();
    createLeftQrcode();
    $('#payCode').modal('show');
    bindEvent();
    viewMode.countDownTime();
//    connectionws();
});


// 请求支付返回数据回调函数
function successCallBack(zfdata) {
    //   console.dir(zfdata);
    //    $('#loding').modal('hide');
    $('#loding').modal('hide');
    //    zfdata = JSON.parse(zfdata);
    var errorCode;
    if (zfdata.error_business_response && zfdata.error_business_response.code) {
        errorCode = zfdata.error_business_response.code;
        // 支付成功返回码位000，其他均为支付失败
        if (errorCode == "0000") { // 
            viewMode.toResult();

        } else if ("50,51,52,53".search(errorCode) != -1) {
            /*  pview.showErroPrompt(zfdata.error_business_response.msg);
              pview.showCardInfo();*/
            $('#tsmodal .modal-body').text(zfdata.error_business_response.msg);
            $('#tsmodal').modal('show');

        } else {

            var pmsg = changeErrorMsg(errorCode);
            if (pmsg == "" || pmsg == undefined) {
                pmsg = "该笔订单支付失败";
            }
            if (errorCode == "59" && zfdata.error_business_response.msg) {
                pmsg = zfdata.error_business_response.msg;
            }
            debugger
            location.href = "../payinstallment/payPrompt.html?msg=" + pmsg + "&simplPC=" + simplPC;
        }
    } else {

    }

}

// 取支付参数
function getPayParameters() {
    var userName = $userName.val();
    var userId = $userId.val();
    var cvn2 = $cvn2.val();
    CardNum = $creditCard.val();
    var xykrq = $dateInput.val();
    var phoneNo = $userPhone.val();
    var verifyCode = $verifyCode.val();
    var parameters = [{
        name: "phoneNo",
        value: phoneNo
    }, {
        name: "creditName",
        value: userName
    }, {
        name: "idno",
        value: userId
    }, {
        name: "creditNo",
        value: CardNum
    }, {
        name: "cvn2",
        value: cvn2
    }, {
        name: "exp",
        value: xykrq
    }, {
        name: "servlet_type",
        value: "create_order"
    }, {
        name: "verifyCode",
        value: verifyCode
    }, {
        name: "orderId",
        value: orderId
    }, {
        name: "sign",
        value: sign
    }, {
        name: "bankCode",
        value: bankCode
    }, {
        name: "tookenkey",
        value: token
    }, {
        name: "applyId",
        value: applyId
    }, {
        name: "payId",
        value: payId
    }]; //请求参数

    return parameters;
}

function pay() {
    $("#loding .modal-body>p").show();
    $('#loding').modal('show');
    var theParameter = getPayParameters();
    $.post(payInstallmentServlet, theParameter, successCallBack);
}


// 确认支付
function submitInfoClick() {
    var checkFormVal = cardInfoForm.check(false);
    //    console.log(checkFormVal);
    if ($("input[type=checkbox]:checked").length == 0) {
        $('#tsmodal .modal-body').text("请勾选'我已阅读并同意《个人消费分期支付合同》'");
        $('#tsmodal').modal('show');
        return;
    }
    if (checkFormVal) {
        pay();
    }
}


// 发送订单金额费率跟后台核实
function sentOrderInfos() {
    // nper:期数 eachMoney:每期还款 totalamount:分期总额  orderIddes:订单号 sign:
    nper = $("#rateSelect").val();
    for (var i = 0, l = rateArray.length; i < l; i++) {
        if (rateArray[i].nper == nper) {
            totalamount = rateArray[i].totalamount;
        }
    }

    var orderInfos = [{
        "name": "nper",
        "value": nper
    }, {
        "name": "eachMoney",
        "value": $("#eachMoney").text()
    }, {
        "name": "totalamount",
        "value": totalamount
    }, {
        "name": "orderIddes",
        "value": orderId
    }, {
        "name": "sign",
        "value": sign
    },{
        "name": "channelNo",
        "value": channelNo    
    }];
    $("#loding .modal-body>p").hide();
    $('#loding').modal('show');
    $.post(LFQ_pcinstallorder_URL, orderInfos, checkOrderInfos);
}

// 验证订单信息返回结果
function checkOrderInfos(cdate) {
    $('#loding').modal('hide');
    console.dir(cdate);
    cdate = JSON.parse(cdate);
    if (cdate.code == "01") {

        viewMode.toFillUserInfo();
    } else {

        location.href = "../payinstallment/payPrompt.html?msg=" + cdate.errormsg + "&simplPC=" + simplPC;
    }

}


// 取分期订单信息
function getRateInfo() {
    //    orderId = decodeURI(wl.QueryString.GetValue("orderId")).replace(/\%2B/g, "+").replace(/\s+/g, "");
    orderId = wl.QueryString.GetValue("orderId")
    sign = wl.QueryString.GetValue("sign");
    var paramter = {
        "orderId": orderId,
        "sign": sign
    };
    $.post(payInstallmentInfoServlet, paramter, infocallback);
}

// 分期信息返回接口
function infocallback(infoData) {
    //    console.dir(infoData);
    clearInterval(autoMoveInterval);
    clearInterval(autoTsqInterval);
    console.dir(infoData);
    //    infoData = JSON.parse(infoData);
    if (infoData && infoData.data && infoData.data.returnUrl) {
        sessionStorage.setItem("returnUrl", infoData.data.returnUrl);
    }
 
    $("#payLoading").hide();
    $(".wrapper").show();
    if (infoData && infoData.code == "0000") {
        viewMode.setOrderInfo(infoData.data);
        simplPC = infoData.data.simplPC;
        amount = infoData.data.amount;
        $(".key_amount").text(amount);
        $("#rqmerName").text(infoData.data.merName)
        $("#rqmerName").text(infoData.data.merName)
        $("#rq-orderid").text(infoData.data.orderId);
        merNo = infoData.data.merNo;
        prdtNo = infoData.data.prdtNo;
        $("#td-spMoney").text(amount)
        rateArray = infoData.data.rateList;
        if(infoData.data.nper){
            nper = infoData.data.nper
        }
        
        unalter =infoData.data.unalter 

        //viewMode.setSelect(rateArray,nper,unalter,amount);

        //rateNumChange();
        viewMode.setReadOnly(infoData.data);
        token = infoData.data.token;
        if(infoData.data.credCardno){ 
            CardNum =infoData.data.credCardno
            $("#xykNo").val(CardNum)
            selectRate()
        }
    } else {
        var ErrorMsg = "未知错误";
        if (infoData.msg) {
            ErrorMsg = infoData.msg;
        }
        location.href = "../payinstallment/payPrompt.html?msg=" + ErrorMsg + "&simplPC=" + simplPC;
    }

}

// 取期数信息
function  selectRate() { //CardNum
  // debugger
  var xykNo = $xykNo.val()
  if(xykNo.length == 16){   
      var _geRateParams = { cardNo: xykNo, orderIdress: orderId}
      if (nper && nper != '') {
        _geRateParams.nper = nper
      }
      // 提示
/*        this.isloading = true
  this.loadingtex = '取期数费率'*/
  $.post(queryRate_URL, _geRateParams, ratesBack);

  }
  

 /* getRateInfo(_geRateParams).then(pmidata => {
    console.log('selectRate..............................')
    console.dir(pmidata)
    this.isloading = false
    let midata = pmidata.data
    // debugger
    if (midata.queryRateDto) {

      this.cardfrom.bankCode = midata.queryRateDto.bankCode
      this.cardfrom.bankName = midata.queryRateDto.bankName
      this.handleQishu(midata.queryRateDto)
    } else {
      debugger
      let errormsg = '该信用卡支持该业务'
      if (midata.error_business_response && midata.error_business_response.msg) {
        errormsg = midata.error_business_response.msg
      }
      this.$vux.alert.show({
        title: '提示',
        content: errormsg
      })
    }
  }).catch(error => {
    this.isloading = false
    this.$vux.alert.show({
      title: '提示',
      content: '期数费率取值失败'
    })
    throw error
  })*/
}
function ratesBack(rates) {
    console.log('ratesBackratesBack---------------------')
    console.dir(rates)
    if(rates.queryRateDto && rates.queryRateDto.bankCode){
        CardNum =rates.queryRateDto.cardNo
        bankCode = rates.queryRateDto.bankCode
        bankName = rates.queryRateDto.bankName
        $("#bankName").val(bankName)
        
    }
    var rateArray = []
    if (rates.queryRateDto.nperList instanceof Array) {
        rateArray = rates.queryRateDto.nperList;

      } else if (rates.queryRateDto.nperList) {
        debugger
        rateArray.push(rates.queryRateDto.nperList)
      }
      if(rateArray.length > 0){
        viewMode.setSelect(rateArray,nper,unalter,amount);
        computerPayMoney()
    }else{
        var errormsg = '该信用卡支持该业务'
        if (rates.error_business_response && rates.error_business_response.msg) {
            errormsg = rates.error_business_response.msg
        }

        $('#tsmodal .modal-body').text(errormsg);
        $('#tsmodal').modal('show');
    }

/*    if(rates.queryRateDto && rates.queryRateDto.nperList){
        rateArray = rates.queryRateDto.nperList;
        viewMode.setSelect(rateArray,nper,unalter,amount);
       // rateNumChange();
    }else{
        var errormsg = '该信用卡支持该业务'
        if (rates.error_business_response && rates.error_business_response.msg) {
            errormsg = rates.error_business_response.msg
        }

        $('#tsmodal .modal-body').text(errormsg);
        $('#tsmodal').modal('show');
    }
    computerPayMoney()*/
}

// 计算总金额、每期支付金额
function computerPayMoney(){
    if(nper && amount){
        var rataInfoObject = getRateInfoObject(nper);
        totalamount = (parseFloat(amount) + parseFloat(amount) * 100 * (parseFloat(rataInfoObject.custRate) * 100) / 1000000 + 0.00001).toFixed(2)
        var eachGoodsMoney = (parseFloat(amount) * 100 / parseInt(nper) / 100).toFixed(2)
        eachPayMoney = (parseFloat(totalamount) * 100 / parseInt(nper) / 100).toFixed(2)
        var eachInterest = ((eachPayMoney * 100 - eachGoodsMoney * 100) / 100).toFixed(2)
        $("#eachMoney").text(eachPayMoney)
        $("#tdesch-spMoney").text(eachGoodsMoney)
        $("#tdesch-sxf").text(eachInterest)
    }
    

}


// 生成微信扫描的二微码
function createQrcode() {
    $("#payqrcode").qrcode({
        width: 200, //宽度 
        height: 200, //高度 
        correctLevel:2,
        text: "https://wxtest.allinpaycard.com/fulibaoweb/#/apply?" + location.search //任意内容 
    });
}

// 生产左边微信扫描的二维码
function createLeftQrcode() {
    $("#left_code").qrcode({
        width: 150, //宽度 
        height: 150, //高度 
        correctLevel:2,
        text: "https://wxtest.allinpaycard.com/fulibaoweb/#/apply?" + location.search //任意内容 
    });
}

// 建立websocket查询扫描结果
/*function connectionws() {
    var stock_request = {
        stocks:["AAPL","MSFT","AMZN","GOOG","YHOO"]
    }
    if (typeof(WebSocket) == "function") {
        var ws = new WebSocket("ws://10.2.235.45:8080/assetbm/ws/orderinstall/sync?orderId=" + orderId);
        ws.onopen = function(e) {
                console.log('Connection to server opened');
                ws.send(JSON.stringify(stock_request)); //stock_request
                console.log("sened a mesg");
            };
            // 处理受到的消息
        ws.onmessage = function(e) {
            var stocksData = JSON.parse(e.data);
            console.log(stocksData);
        };
    }
}*/

// 显示二维码
function showQrcode() {
    $('#payCode').modal('show');
}

// 分期数改变
function rateNumChange() {
    nper = $rateSelect.val();  // nper
    var rataInfoObject = getRateInfoObject(nper);
    viewMode.setRate(rataInfoObject);
    computerPayMoney()

}

// 查找费率
function getRateInfoObject(rateVal) {
    var rataInfoObject = {};
    channelNo = '';
    for (var i = 0, l = rateArray.length; i < l; i++) {
        if (rateArray[i].nper == rateVal) {
            rataInfoObject = rateArray[i];
            if(rateArray[i].channelNo){
                channelNo = rateArray[i].channelNo;
            }
            
        }
    }

    return rataInfoObject;
}

function initValue() {
    $userName = $("#userName");
    $cardInfo = $("#cardInfo");
    $countBox = $("#countBox");
    $rateSelect = $("#rateSelect");
    $userId = $("#userId");
    $cvn2 = $("#cvn2");
    $dateInput = $("#dateInput");
    $userPhone = $("#userPhone");
    $verifyCode = $("#verify-code");
    $creditCard = $("#creditCard");
    $xykNo = $('#xykNo');
    $vCodeButton = $("#vCodeButton");
    wl.QueryString.Initial();
}

// 绑定事件
function bindEvent() {
    $xykNo.on("keyup",selectRate);
    $rateSelect.on("change", rateNumChange);
    $("#submitInfo").on("click", submitInfoClick);
    $("#vCodeButton").on("click", function() {
        var userName = $userName.val();
    var userId = $userId.val();
    var cvn2 = $cvn2.val();
    CardNum = $creditCard.val();
    var xykrq = $dateInput.val();
    var phoneNo = $userPhone.val();
    var verifyCode = $verifyCode.val();
        var _params = {
            hpNo :$("#userPhone").val().replace(/ /g, ""), //手机号码
            orderIddes:orderId, //加密订单号
            orderid:orderId,
            idNo:userId, //身份证ID
            expiryDate:xykrq, // 信用卡有用效期
            merNo:merNo, //商户号
            custName:userName, //用户姓名
            cardNo:CardNum, //信用卡号
            cvn2:cvn2, //银行卡cv2
            stageCount:nper, //分期数
            bankCode:bankCode, //银行编码
            stageAmt:totalamount, //分期总金额
            channelNo:channelNo, //渠道
            prdtNo:prdtNo  // 产品号
        }
        getVerifyCode(_params);
    });
    $("#toFill").on("click", sentOrderInfos);

}





//请求 验证码
function getVerifyCode(_params) {
    viewMode.canGetCode();
    if ($vCodeButton.hasClass("btn-ok")) { //发送短信 禁用60秒

        //发送短信
        // 禁用60秒
        var $vCodeButton2 = $("#vCodeButton2")
        $vCodeButton.removeClass("btn-ok");
       // $vCodeButton.text("重新获取(" + getVerifyCodeDJS + "S)");
        $("#vCodeButton1").text("重新获取")
        $(".vCodeButton2").css({display:"inline-block"})
        $vCodeButton2.text(getVerifyCodeDJS)
        var setIntervarHandle = setInterval(function() {
            getVerifyCodeDJS--;
            //$vCodeButton.text("重新获取(" + getVerifyCodeDJS + "s)");
            $vCodeButton2.text(getVerifyCodeDJS)
            if (getVerifyCodeDJS == 0) {
                //$vCodeButton.text("重新获取");
                $(".vCodeButton2").css({display:"none"})
                $vCodeButton2.text("")
                clearInterval(setIntervarHandle);
                $vCodeButton.addClass("btn-ok");
                getVerifyCodeDJS = 60;
            };
        }, 1000);

        getVerificationCode(_params);
    }
}


// 发送验证码请求
function getVerificationCode(_params) {
    $("#loding .modal-body>p").show();
    $('#loding').modal('show');
    var url = LFQ_SMS_SEND_URL;
    var hp_no = $userPhone.val().replace(/ /g, "");
    var id_no = $userId.val().replace(/ /g, "");
    _params.hp_no = hp_no;
    _params.idno = id_no;
    $.post(url, _params, function(resData1) {
        $('#loding').modal('hide');
        debugger
        if (resData1.code !== '0000') {
            $('#tsmodal .modal-body').text(resData1.msg);
            $('#tsmodal').modal('show');
        }
        debugger
        if (resData1.data && resData1.data.applyId) {
          applyId = resData1.data.applyId
          payId = resData1.data.payId
        }

    });
}


// 根据后台返回的错误码修改提示语
function changeErrorMsg(errorCode) {

    var codeMsg = {
        "4001": "无法获得产品信息",
        "4002": "订单创建失败",
        "4003": "输入有误,请重新输入",
        "4004": "当前订单状态无法重新生成订单",
        "4005": "订单信息不存在",
        "4006": "订单重新生成失败",
        "4007": "扫码商户和进行消费的商户非同一商户,不能消费",
        "4008": "当前订单已失效,请重新生成",
        "4009": "该笔订单正在处理中，请稍后....",
        "4010": "金额不一致，不能消费",
        "4011": "订单消费失败",
        "4012": "当前订单非可消费状态",
        "4013": "该商品不支持部分退货",
        "4014": "退货失败",
        "4015": "无法获取小通分期的商户号,请先配置该商户小通分期的商户号",
        //          "4016":"无法获得总部成本扣率,请先设置n期的总部成本扣率",
        "4016": "无法获得总部成本扣率，暂不支持该分期期数",
        "4017": "无法获得供应商成本扣率",
        "4018": "验签错误",
        "4019": "商户信息不存在",
        "4020": "该笔订单已做过交易,无需重复交易",
        "4021": "该笔订单不允许撤销",
        "4022": "该笔订单超过了允许撤销的日期",
        "4023": "撤销失败",
        "4024": "当前订单已经处于退货审核中,不能撤销",
        "4025": "无法获得总部营业员分成比例,请先设置n期的营业员分成比例",
        "4026": "退货的商户和消费商户非同一商户,不能退货",
        "4027": "无法获取订单商户号",
        //以下为银骏交易失败返回码
        "0101": "交易失败。",
        "0103": "通讯超时",
        "0105": "交易已受理，请稍后查询交易结果",
        "0110": "报文格式错误",
        "0111": "验证签名失败",
        "0112": "重复交易",
        "0113": "身份证格式错误",
        "0114": "手机号格式错误",
        "0115": "CVN格式错误",
        "0116": "有效期格式错误",
        "0117": "该卡不支持分期业务",
        "0118": "商户不支持的分期期数",
        "0119": "卡有效期不足以进行分期支付，请重新换卡",
        "0132": "无此交易权限",
        "0134": "查无此交易",
        "0138": "商户密码错误",
        "0140": "单笔交易金额不在规定范围内",
        "0141": "超过个人借款总金额",
        "0142": "超过个人在单个商户单日交易总金额",
        "0144": "该卡因多次余额不足交易受限",
        "0151": "令牌失效，无效的提交",
        "0152": "用户提交的数据校验出错",
        "0153": "超过有效时间",
        "0170": "持卡人姓名、身份证或手机号输入错误，验证失败",
        "0199": "未知错误",
        "0201": "交易失败",
        "0210": "业务数据错误",
        "0220": "商户不存在",
        "0221": "商户无效",
        "0299": "未知错误",
        "0301": "交易失败",
        "0302": "系统维护中请稍后再试",
        "0303": "交易通讯超时",
        "0304": "交易超时 ",
        "0305": "交易已受理，接收通讯异常",
        "0310": "通讯异常，报文格式错误",
        "0311": "通讯异常，验证签名失败",
        "0312": "重复交易",
        "0313": "通讯异常，交易要素缺失",
        "0314": "批量文件格式错误",
        "0330": "交易失败，请更换其他卡支付",
        "0331": "通讯异常，商户状态不正确",
        "0332": "请使用有银联标识的信用卡",
        "0333": "交易金额超限",
        "0334": "查无此交易",
        "0335": "原交易状态不正确",
        "0336": "与原交易信息不符，请重新操作",
        "0337": "已超过最大查询次数或操作过于频繁",
        "0338": "风险受限",
        "0339": "交易不在受理时间范围内",
        "0340": "绑定关系检查失败",
        "0341": "批量状态不正确，无法下载",
        "0342": "扣款成功但交易超过规定支付时间",
        "0360": "交易失败，详情请咨询您的发卡行",
        "0361": "输入的卡号无效，请确认后输入",
        "0362": "交易失败，发卡银行不支持该交易，请更换其他银行卡",
        "0363": "卡状态不正确",
        "0364": "卡上的余额不足",
        "0365": "输入的密码、有效期或CVN2有误，交易失败",
        "0366": "持卡人身份信息或手机号输入不正确，验证失败",
        "0367": "密码输入次数超限",
        "0368": "您的银行卡暂不支持该业务",
        "0369": "您的输入超时，交易失败",
        "0370": "交易超时",
        "0371": "动态口令或短信验证码校验失败",
        "0372": "尚未开通无卡支付功能，请联系银行开通",
        "0373": "该卡已过有效期",
        "0374": "扣款成功，销账未知",
        "0375": "扣款成功，销账失败",
        "0376": "需要验密开通",
        "0377": "银行卡未开通认证支付",
        "0378": "发卡行交易权限受限，详情请咨询您的发卡行"
    };
    var errorMsg = "";
    if (codeMsg[errorCode]) {
        errorMsg = codeMsg[errorCode];
    }

    return errorMsg;
}